<?php

namespace app\admin\controller;

use think\Request;
use app\admin\controller\Msg;
class Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function parseWhere(Request $request){
        $map = [];
        foreach($request->param() as $k=>$v){
            switch($k){
                case 'like':
                    foreach($v as $field=>$val){
                        if(!empty($val)) $map[] = [$field,'like',"%${val}%"];
                    }
                    break;
                case 'equal':
                    foreach($v as $field=>$val){
                        if(!empty($val)) $map[] = [$field,'=',$val];
                    }
                    break;
            }
        }
        return $map;
    }
    public function index(Request $request)
    {
        $p = ('\app\admin\model\\'.$request->controller());
        $m = new $p;
        $map = $this->parseWhere($request);
        $list = $m->order('id', 'desc')->where($map)->paginate(10);
        return json([
            'code'=>0,
            'count'=>$list->total(),
            'msg'=>'',
            'data'=>$list->items()
        ]);
    }

    public function dict(Request $request){
        $p = ('\app\admin\model\\'.$request->controller());
        $m = new $p;
        $data = $m->field('id,name')->select();
        $dicts = [];
        foreach($data as $r){
            $dicts[$r['id']] = $r['name'];
        }
        return msg::success($dicts);
    }


    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $p = ('\app\admin\model\\'.$request->controller());
        $m = new $p;
        $m->save($_POST);
        return msg::success('save');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $p = ('\app\admin\model\\'.$request->controller());
        $m = new $p;

        parse_str(file_get_contents('php://input'),$put);
        //$nav->name = $request->param('name');
        $m->where('id',$id)->save($put);
        return msg::success();
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $p = ('\app\admin\model\\'.request()->controller());
        $m = new $p;
        $m->where('id','in',explode(',',$id))->delete();
        return msg::success();
    }


    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }
}
